//
//  MLCacheHelper.m
//  hehe
//
//  Created by Robin on 16/3/7.
//  Copyright © 2016年 HolyShit. All rights reserved.
//

#import "MYCacheHelper.h"

static NSString *const HSDataCacheName = @"HSDataCacheName";
static const NSUInteger HSDataCacheLimint = 10;//10m

@interface MYCacheHelper ()

@property (nonatomic, strong) YYCache *cache;

@end

@implementation MYCacheHelper

+ (MYCacheHelper *)shareHelper
{
    static dispatch_once_t onceToken;
    static MYCacheHelper *helper;
    dispatch_once(&onceToken, ^{
        helper = [MYCacheHelper new];
        [helper configCache];
    });
    return helper;
}

/**
 配置缓存
 */
- (void)configCache
{
    self.cache = [YYCache cacheWithName:HSDataCacheName];
    self.cache.diskCache.costLimit = HSDataCacheLimint * 1024 * 1024;//设置最大缓存，10m
    self.cache.diskCache.ageLimit = 2 * 24 * 3600;//设置过期时间，2天
}

-(void)my_saveCacheWithObject:(id)object key:(NSString *)key
{
    NSString *cackeKey = [NSString stringWithFormat:@"%@_%@", key, @"user_id"];
    if([object isKindOfClass:[NSArray class]]){
        [self.cache.diskCache setObject:[NSKeyedArchiver archivedDataWithRootObject:object] forKey:cackeKey];
    }
    else{
        [self.cache.diskCache setObject:[object modelToJSONData] forKey:cackeKey];
    }
}

-(id)my_cacheWithKey:(NSString *)key clazz:(Class)clazz
{
    NSString *cackeKey = [NSString stringWithFormat:@"%@_%@", key, @"user_id"];
    YYCache *cache = [YYCache cacheWithName:HSDataCacheName];
    NSData *data = (NSData *)[cache.diskCache objectForKey:cackeKey];
    if(clazz == [NSArray class]){
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    else if(clazz == [NSDictionary class]){
        return [data jsonValueDecoded];
    }
    else if(clazz == [NSString class]){
        return [data utf8String];
    }
    return data;
}

@end
